package org.vt.ece4564.pcw.textinclass;

import org.vt.ece4564.pcw.textinclass.R;

import android.os.Bundle;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class LoginActivity extends Activity  implements OnClickListener {
	
	private EditText usernameEditText_;
	private EditText passwordEditText_;
	
	private Button loginButton_;
	
	private ProgressBar progressBar_;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        SharedPreferences settings = getSharedPreferences("TextInClassPrefs", MODE_PRIVATE);
        
        boolean registered = settings.getBoolean("registered", false);
        
        // Not the first time logging in
        if (registered) { 
        	setContentView(R.layout.activity_login);
        
        	usernameEditText_ = (EditText) findViewById(R.id.usernameEditText);
        	passwordEditText_ = (EditText) findViewById(R.id.passwordEditText);
        	loginButton_ = (Button) findViewById(R.id.loginButton);
        	progressBar_ = (ProgressBar) findViewById(R.id.loginProgressBar);
        
        	loginButton_.setOnClickListener(this);
        	
        	progressBar_.setEnabled(false);
        	progressBar_.setVisibility(View.INVISIBLE);
        	
        }
        else {
        	Intent intent = new Intent(this, RegisterUserActivity.class);
        	
        	startActivity(intent);
        }
        
    }

	public void onClick(View v) {
		
		Button clicked = (Button) v;
		
		if (clicked == loginButton_) {
			String username = usernameEditText_.getText().toString();
			String password = passwordEditText_.getText().toString();
			
			loginButton_.setEnabled(false);
			progressBar_.setVisibility(View.VISIBLE);
			
		    String deviceId = PhoneIDGenerator.getPhoneID(this);
		    
		    Log.d("DeviceId", deviceId);
			
			Log.d("here", "here");
			
			LoginRequest loginRequest = new LoginRequest(username, password, deviceId, this);
			
			Log.d("there", "there");
			
			loginRequest.execute();
		}
		else {
			Toast toast = Toast.makeText(getApplicationContext(), 
					"An Error Occurred", Toast.LENGTH_SHORT);
			
			toast.show();
		}
		
	}
	
	public void resetScreen() {
		usernameEditText_.setText("");
		passwordEditText_.setText("");
		progressBar_.setVisibility(View.INVISIBLE);
		loginButton_.setEnabled(true);
	}

}
